// pages/mine/mine.js
var shihan = require('../../common/fetch');
var config = require('../../common/config');
var time, token, open_id, range, range3, rangeleft, float_timer, float_time;
var gopage = 0, float = 0, signflag = true, sceneres = {};
var app = getApp();
var winScale = 750 / app.data.deviceInfo.windowWidth;
Page({

  /**
   * 页面的初始数据 sh_certificate
   */
  data: {
    centerflag: true,
    partnerflag: false,
    showLoading: true,
    btndisabled: '',
    signyes: false,
    signnick: true,
    concatflag: true,
    shbnmineflag: true,
    toast_flag: false,
    dialogflag: true,
    filterConflag: false,
    downloadimgflag: true,
    setupdownloadimgflag: true,
    messageids: '',
    peopleinfo: '',
    messageidsfalg: false,
    certificatenum: '',
    userinfo_code: '',
    cue_flag: false,
    defaults: 'https://img-oss.shihanbainian.com/shihan2/index/defaults.png'
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function(options) {
    var that = this
    that.setData({
      offoptions: options
    })
    that.checknetword()
    that.publicinfo()
    if (app.data.setupdownloadimgflag == 0) {
      app.data.setupdownloadimgflag = 1
      that.openCertificate();
    }
    range = 900 / winScale;
    rangeleft = 750 / winScale;
    var animation = wx.createAnimation({
      duration: 350,
      timingFunction: 'ease-in-out',
    });
    this.animation = animation;
    var animation1 = wx.createAnimation({
      duration: 350,
      timingFunction: 'ease-in-out',
    });
    this.animation1 = animation1;
    range3 = 1160 / winScale;
    var animation3 = wx.createAnimation({
      duration: 350,
      timingFunction: 'ease-in-out',
    });
    this.animation3 = animation3;
    app.wechatSwitch().then(function(wechat_switch) { //是否打开微信授权开关
      app.commonLogin(sceneres, wechat_switch)
    })
  },
  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function() {
    var that = this
    token = wx.getStorageSync('token');
    that.checknetword(that.data.offoptions)
    if (token) {
      if (that.data.shbnmineflag) {
        if (token) {
          that.mypeopleinfo();
        }
      } else {
        that.partnermine();
      }
    } else {
      that.mypeopleinfo();
    }
    var lastIds = wx.getStorageSync('lastIds') || '';
    var messageids = wx.getStorageSync('messageids') || '';
    if (messageids && Object.keys(messageids).length > 0) {
      if (lastIds) {
        if (lastIds.sh_activity_lastid > messageids.sh_activity_id || lastIds.sh_customer_salesrule_lastid > messageids.sh_customer_salesrule_id || lastIds.sh_partner_inform_lastid > messageids.sh_partner_inform_id) {
          that.setData({
            messageidsfalg: true
          })
        } else {
          that.setData({
            messageidsfalg: false
          })
        }
      } else {
        that.setData({
          messageidsfalg: true
        })
      }
    } else {
      wx.setStorage({
        key: 'messageids',
        data: {
          sh_activity_id: '',
          sh_customer_salesrule_id: '',
          sh_partner_inform_id: ''
        }
      })
      that.setData({
        messageids: {
          sh_activity_id: '',
          sh_customer_salesrule_id: '',
          sh_partner_inform_id: ''
        }
      })
    }
    wx.login({
      success: function(res) {
        that.setData({
          userinfo_code: res.code
        })
      }
    })
  },
  refreshdata: function() {
    this.setData({
      showLoading: true
    })
    this.onShow();
  },
  checknetword: function() {
    var that = this;
    wx.getNetworkType({
      success: function(res) { // wifi/2g/3g/4g/unknown(Android下不常见的网络类型)/none(无网络)
        // console.log(res)
        if (res.networkType == 'none') {
          that.setData({
            isoffline: false,
            showLoading: false
          })
        } else {
          that.setData({
            isoffline: true,
            showLoading: true
          })
        }
      }
    })
  },
  isLogin: function() {
    token = wx.getStorageSync('token');
    if (!token) {
      app.commonNoLogin()
    }
  },
  agentEntry: function() { //代理商入口
    wx.navigateTo({
      url: '/pages/business/index/index',
    })
  },
  modaddress: function() {
    token = wx.getStorageSync('token');
    if (!token) {
      this.getauthorize()
    } else {
      if (this.data.peopleinfo.sh_status == 1) {
        wx.navigateTo({
          url: '/pages/modaddress/modaddress?adtype=mine'
        })
      } else {
        shihan.showToast.call(this, this.data.peopleinfo.sh_freeze_label);
      }
    }
  },
  launchAppError: function(e) {
    console.log(e.detail.errMsg)
  },
  gologin: function() {
    this.getauthorize()
    console.log(config);
  },
  onGotUserInfo: function(e) { //更新资料 update_wechat_data
    // app.moniLogin(sceneres, e)
    var data = {},
      that = this;
    if (e.detail.encryptedData) {
      if (that.data.userinfo_code) {
        data['code'] = that.data.userinfo_code;
        data['iv'] = e.detail.iv;
        data['encrypted_data'] = e.detail.encryptedData;
        shihan.sendRequest(config.update_wechat_data, 'POST', data)
          .then(function(res) {
            if (res.data.code == 0) {
              that.onShow()
              wx.login({
                success: function(res) {
                  that.setData({
                    userinfo_code: res.code
                  })
                }
              })
            } else { //更新资料失败
              if (res.data.code == 8) {
                res.data.msg = '同步出错了，请重试哦'
              }
              shihan.showToast.call(that, res.data.msg);
            }
          }, function(error) {
            console.log(error);
          });
      }
    }
  },
  mygroup: function() {
    token = wx.getStorageSync('token');
    if (!token) {
      this.getauthorize()
    } else {
      if (this.data.peopleinfo.sh_status == 1) {
        wx.navigateTo({
          url: '/pages/other/mygroup/mygroup',
        })
      } else {
        shihan.showToast.call(this, this.data.peopleinfo.sh_freeze_label);
      }
    }
  },
  minenews: function() {
    var actId = '',
      salId = '',
      infId = '';
    if (this.data.peopleinfo && this.data.peopleinfo.sh_message_ids) {
      actId = this.data.peopleinfo.sh_message_ids.sh_activity_id;
      salId = this.data.peopleinfo.sh_message_ids.sh_customer_salesrule_id;
      infId = this.data.peopleinfo.sh_message_ids.sh_partner_inform_id;
    }
    wx.navigateTo({
      url: '/pages/other/minenews/minenews?actId=' + actId + '&salId=' + salId + '&infId=' + infId,
    })
  },
  mycollection: function() {
    token = wx.getStorageSync('token');
    if (!token) {
      this.getauthorize()
    } else {
      if (this.data.peopleinfo.sh_status == 1) {
        wx.navigateTo({
          url: '/pages/other/mycollection/mycollection',
        })
      } else {
        shihan.showToast.call(this, this.data.peopleinfo.sh_freeze_label);
      }
    }
  },
  openmyhistory: function() {
    wx.navigateTo({
      url: '/pages/other/minehistory/minehistory',
    })
  },
  myorder: function(e) {
    token = wx.getStorageSync('token');
    if (!token) {
      this.getauthorize()
    } else {
      wx.navigateTo({
        url: '/pages/myorder/myorder?orderindex=' + e.currentTarget.dataset.index,
      })
    }
  },
  logoutfn: function() {
    shihan.sendRequest(config.logout, 'POST', {})
      .then(function(res) {
        console.log(res)
      }, function(error) {
        console.log(error);
      });
  },
  expenseopen: function() {
    token = wx.getStorageSync('token');
    if (!token) {
      this.getauthorize()
    } else {
      if (this.data.peopleinfo.sh_status == 1) {
        wx.navigateTo({
          url: '/pages/other/expensecard/expensecard'
        })
      } else {
        shihan.showToast.call(this, this.data.peopleinfo.sh_freeze_label);
      }
    }
  },
  opencoupon: function() {
    token = wx.getStorageSync('token');
    if (!token) {
      this.getauthorize()
    } else {
      if (this.data.peopleinfo.sh_status == 1) {
        wx.navigateTo({
          url: '/pages/other/coupon/coupon'
        })
      } else {
        shihan.showToast.call(this, this.data.peopleinfo.sh_freeze_label);
      }
    }
  },
  openbupiao: function() {
    token = wx.getStorageSync('token');
    if (!token) {
      this.getauthorize()
    } else {
      if (this.data.peopleinfo.sh_status == 1) {
        wx.navigateTo({
          url: '/pages/other/bupiao/bupiao'
        })
      } else {
        shihan.showToast.call(this, this.data.peopleinfo.sh_freeze_label);
      }
    }
  },
  openbalance: function() {
    token = wx.getStorageSync('token');
    if (!token) {
      this.getauthorize()
    } else {
      if (this.data.peopleinfo.sh_status == 1) {
        wx.navigateTo({
          url: '/pages/other/balance/balance'
        })
      } else {
        shihan.showToast.call(this, this.data.peopleinfo.sh_freeze_label);
      }
    }
  },
  openseting: function() {},
  bindphone: function(e) {
    var word;
    // this.getauthorize()
    var num = e.currentTarget.dataset.num
    if (num > 0) {
      word = '请在世瀚百年APP内查看售后进度（使用微信登录）'
    } else {
      word = '请在世瀚百年APP内申请售后服务（使用微信登录）'
    }
    wx.showModal({
      title: "提示",
      content: word,
      confirmText: "确认",
      confirmColor: "#c40000",
      showCancel: true,
      success: function(res) {
        if (res.confirm) {
          wx.navigateTo({
            url: '/pages/strategyinfo/strategyinfo?share=0&nologin=1&url=' + encodeURIComponent(config.commonmoburl +'other/downloadapp.html')
          })
        }
      }
    })
  },
  getauthorize: function() {
    app.commonNoLogin()
  },
  downloadapp: function() {
    wx.navigateTo({
      url: '/pages/strategyinfo/strategyinfo?share=0&nologin=1&url=' + encodeURIComponent(config.commonmoburl + 'other/downloadapp.html')
    })
  },
  helpcenter: function() {
    wx.navigateTo({
      url: '/pages/strategyinfo/strategyinfo?share=0&nologin=1&url=' + encodeURIComponent(this.data.peopleinfo.sh_helpcenter)
    })
  },
  openaboutus: function() {
    wx.navigateTo({
      url: '/pages/strategyinfo/strategyinfo?share=0&nologin=1&url=' + encodeURIComponent(this.data.peopleinfo.sh_about_url)
    })
  },
  openArticle: function (e) {
    wx.navigateTo({
      url: '/pages/strategyinfo/strategyinfo?share=0&nologin=1&url=' + encodeURIComponent(e.currentTarget.dataset.url)
    })
  },
  openweb: function(e) {
    // if (e.currentTarget.dataset.url) {
    //   wx.navigateTo({
    //     url: '/pages/strategyinfo/strategyinfo?share=0&nologin=1&url=' + encodeURIComponent(e.currentTarget.dataset.url)
    //   })
    // }
    wx.navigateTo({
      url: '/pages/other/cooperation/cooperation',
    })
  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function() {

  },
  mypeopleinfo: function() {
    var that = this
    shihan.sendRequest(config.login_customer_info, 'POST', {})
      .then(function (res) {
        if (res.data.code == 0) {
          var messageids = res.data.data.sh_message_ids;
          var lastIds = wx.getStorageSync('lastIds') || '';
          if (messageids && Object.keys(messageids).length > 0) {
            if (lastIds) {
              if (lastIds.sh_activity_lastid > messageids.sh_activity_id || lastIds.sh_customer_salesrule_lastid > messageids.sh_customer_salesrule_id || lastIds.sh_partner_inform_lastid > messageids.sh_partner_inform_id) {
                that.setData({
                  messageidsfalg: true
                })
              } else {
                that.setData({
                  messageidsfalg: false
                })
              }
            } else {
              that.setData({
                messageidsfalg: true
              })
            }
          }
          if (Number(res.data.data.sh_balance) == 0) {
            res.data.data.sh_balance = Number(res.data.data.sh_balance).toFixed(2)
          }
          if (Number(res.data.data.sh_bupiao) == 0) {
            res.data.data.sh_bupiao = Number(res.data.data.sh_bupiao).toFixed(2)
          }
          config.nickName = res.data.data.sh_nick_name;
          config.sh_is_partner = res.data.data.sh_is_partner || 0;
          that.setData({
            peopleinfo: res.data.data,
            ispartner: res.data.data.sh_is_partner || 0
          })
          if (app.data.partnerflag == 1) {
            app.data.partnerflag = 0;
            that.openpartnercenter();
          }
        }
        that.setData({
          showLoading: false
        })
        wx.stopPullDownRefresh()
      }, function (error) {
        console.log(error);
      });
  },
  concatkefu: function() {
    this.animation.translateY(-range).step();
    this.setData({
      filterConflag: true,
      animationData: this.animation.export()
    })
  },
  closeconcat: function() {
    this.animation.translateY(range).step();
    this.setData({
      filterConflag: false,
      animationData: this.animation.export()
    })
  },
  phonecall: function() {
    var that = this
    wx.makePhoneCall({
      phoneNumber: that.data.peopleinfo.sh_custom_service_tel //仅为示例，并非真实的电话号码
    })
  },
  publicinfo: function() { //configinfo
    var that = this
    shihan.sendRequest(config.configinfo, 'GET', {})
      .then(function(res) {
        that.setData({
          configinfo: res.data.data
        })
      }, function(error) {
        console.log(error);
      });
  },
  openpartnercenter: function() {
    if (this.data.peopleinfo.sh_status == 1) {
      this.setData({
        centerflag: false,
        partnerflag: true
      })

      this.setData({
        shbnmineflag: false
      })
      this.partnermine();
    } else {
      shihan.showToast.call(this, this.data.peopleinfo.sh_freeze_label);
    }
  },
  myminecenter: function() {
    this.setData({
      shbnmineflag: true
    })
    this.setData({
      centerflag: true,
      partnerflag: false
    })
  },
  partnermine: function() {
    var that = this
    shihan.sendRequest(config.partner, 'POST', {})
      .then(function(response) {
        // console.log(response);
        if (response.data.code == 0) {
          if (Number(response.data.data.sh_month_sales_revenue) == 0) {
            response.data.data.sh_month_sales_revenue = Number(response.data.data.sh_month_sales_revenue).toFixed(2)
          }
          if (Number(response.data.data.sh_balance) == 0) {
            response.data.data.sh_balance = Number(response.data.data.sh_balance).toFixed(2)
          }
          if (Number(response.data.data.sh_wait_account_price) == 0) {
            response.data.data.sh_wait_account_price = Number(response.data.data.sh_wait_account_price).toFixed(2)
          }
          if (Number(response.data.data.sh_already_account_price) == 0) {
            response.data.data.sh_already_account_price = Number(response.data.data.sh_already_account_price).toFixed(2)
          }
          if (Number(response.data.data.sh_refund_price) == 0) {
            response.data.data.sh_refund_price = Number(response.data.data.sh_refund_price).toFixed(2)
          }
          if (Number(response.data.data.sh_sales_total) == 0) {
            response.data.data.sh_sales_total = Number(response.data.data.sh_sales_total).toFixed(2)
          }
          // response.data.data.sh_classrooms = [
          //   {
          //     sh_id: 8,
          //     sh_name: "优秀案例2",
          //     sh_type: "优秀案例",
          //     sh_url: "https://m-test.shihanbainian.com/h5/partner/classroom.html?id=8"
          //   }
          // ]
          // response.data.data.sh_classrooms.length = 0;
          if (response.data.data.sh_classrooms && response.data.data.sh_classrooms.length>0) {
            var arr_index = 0;
            var classrooms = response.data.data['sh_new_classrooms'] = [];
            response.data.data.sh_classrooms.forEach(function (el, index) {
              if (!classrooms[arr_index]) { classrooms[arr_index] = []; }
              classrooms[arr_index].push(el);
              if (classrooms[arr_index].length == 3) {
                arr_index++
              }
            })
          }
          // console.log(response.data.data)
          
          config.userimg = response.data.data.sh_headimgurl;
          config.nickName = response.data.data.sh_nick_name;
          that.setData({
            routinebg: response.data.data.sh_certificate,
            partnercode: response.data.data.sh_partner_qrcode,
            certificatenum: response.data.data.sh_num_code,
            partnerinfo: response.data.data
          })
          if (!that.data.shareImage) {
            that.setData({
              painting: {
                width: 600,
                height: 900,
                clear: true,
                views: [
                  {
                    type: 'image',
                    url: that.data.routinebg,
                    top: 0,
                    left: 0,
                    width: 600,
                    height: 900
                  },
                  {
                    type: 'text',
                    content: config.nickName,
                    fontSize: 28,
                    color: '#444',
                    textAlign: 'center',
                    top: 454,
                    left: 300,
                    bolder: true
                  },
                  {
                    type: 'image',
                    url: config.userimg,
                    top: 332,
                    left: 240,
                    width: 120,
                    height: 120,
                    borderRadius: 60
                  },
                  {
                    type: 'image',
                    url: that.data.partnercode || 'https://img-oss.shihanbainian.com/shihan2/index/defaults.png',
                    top: 575,
                    left: 240,
                    width: 120,
                    height: 120,
                    borderRadius: 60
                  },
                  {
                    type: 'text',
                    content: '证书编号：' + that.data.certificatenum,
                    fontSize: 20,
                    color: '#c4b06c',
                    textAlign: 'left',
                    top: 765,
                    left: 196
                  }
                ]
              }
            })
          }
          float = 0;//间隔时间显示重置
          clearInterval(float_time);
          clearInterval(float_timer);
          if (response.data.data.sh_float_partners && response.data.data.sh_float_partners.length>0) {
            that.showCueMoney();//间隔时间显示某某某赚佣金
          }
        }
        that.setData({
          showLoading: false
        })
        wx.stopPullDownRefresh()
      }, function(error) {
        console.log(error);
        that.setData({
          showLoading: false
        })
      });
  },
  eventGetImage: function (event) {
    // console.log(event)
    const { tempFilePath, errMsg } = event.detail;
    if (errMsg === 'canvasdrawer:ok') {
      this.setData({
        shareImage: tempFilePath
      })
    }
    wx.hideLoading()
  },
  crashamount: function() {
    wx.showModal({
      title: "提示",
      content: '请在世瀚百年APP内申请提现服务（使用微信登录）',
      confirmText: "确认",
      confirmColor: "#c40000",
      showCancel: true,
      success: function(res) {
        if (res.confirm) {
          wx.navigateTo({
            url: '/pages/strategyinfo/strategyinfo?share=0&nologin=1&url=' + encodeURIComponent(config.commonmoburl + 'other/downloadapp.html')
          })
        }
      }
    })
  },
  openmyteam: function() {
    wx.navigateTo({
      url: '/pages/partner/myteam/myteam?money=' + this.data.partnerinfo.sh_partner_invite_amount
    })
  },
  openMyclass: function (e) {
    wx.navigateTo({
      url: '/pages/strategyinfo/strategyinfo?share=0&nologin=1&url=' + encodeURIComponent(e.currentTarget.dataset.url)
    })
  },
  openmyfans: function() {
    wx.navigateTo({
      url: '/pages/partner/myfans/myfans'
    })
  },
  openmyextension: function() {
    wx.navigateTo({
      url: '/pages/partner/extensionlist/extensionlist'
    })
  },
  openmycommission: function() {
    wx.navigateTo({
      url: '/pages/partner/commission/commission?money=' + this.data.partnerinfo.sh_partner_invite_amount + '&img=' + this.data.partnerinfo.sh_commission_image
    })
  },
  openmyselllist: function() {
    wx.navigateTo({
      url: '/pages/partner/salestotal/salestotal'
    })
  },
  openmycommissiondetail: function(e) {
    wx.navigateTo({
      url: '/pages/partner/commissiondetail/commissiondetail?index=' + e.currentTarget.dataset.index
    })
  },
  openmytotalreward: function() {
    wx.navigateTo({
      url: '/pages/partner/totalreward/totalreward'
    })
  },
  openmytutorwechat: function() {
    wx.navigateTo({
      url: '/pages/partner/tutorwechat/tutorwechat?codeimg=' + this.data.partnerinfo.sh_tutor_wechat_qrcode
    })
  },
  openmynews: function() {
    wx.navigateTo({
      url: '/pages/partner/mynews/mynews'
    })
  },
  openStorycircle: function () {
    wx.navigateTo({
      url: '/pages/partner/storycircle/storycircle'
    })
  },
  openClassroom: function (e) {
    wx.navigateTo({
      url: '/pages/partner/classroom/classroom?index='+ e.currentTarget.dataset.index
    })
  },
  openCertificate: function () {
    if (!this.data.shareImage) {
      wx.showLoading({
        title: '绘制中',
        mask: true
      })
    }
    this.setData({
      setupdownloadimgflag: false
    })
  },
  showCueMoney: function () {//间隔时间显示某某某赚佣金
    var float_partners = this.data.partnerinfo.sh_float_partners;
    float_timer = setInterval(() => {
      if (float == float_partners.length) {
        clearInterval(float_time);
        clearInterval(float_timer);
        this.setData({
          cue_flag: !this.data.cue_flag
        })
        return
      } else {
        this.setData({
          cue_flag: !this.data.cue_flag,
          cue_img: float_partners[float].sh_headimgurl,
          cue_word: float_partners[float].sh_text
        })
      }
    }, 3000)
    float_time = setTimeout(() => {
      float++
    }, 3000)
  },
  closeimg: function() {
    this.setData({
      setupdownloadimgflag: true
    })
  },
  downloadimg: function() {
    shihan.saveImage(this.data.shareImage); //保存图片
  },
  jumpadvert: function(e) { //广告位跳转
    app.AdSkipper(e)
  },
  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function() {},

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function() {
    token = wx.getStorageSync('token');
    if (token) {
      if (this.data.shbnmineflag) {
        this.mypeopleinfo();
      } else {
        this.partnermine();
      }
    } else {
      this.mypeopleinfo();
    }
  }
})